<template>
  <view class="login-page">
    <uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
    <button type="primary" class="login-button" @click ="getUserProfile">一鍵登入</button>
    <text class="login-text">登入即可开启愉快体驗</text>
  </view>
</template>

<script>
  import {mapMutations,mapState} from 'vuex'
  export default {
    name:"loginPage",
    data() {
      return {
      };
    },
    methods:{
      ...mapMutations('user',['updateUserInformation','updateToken','updateRedirectInfo']),
      
      getUserProfile(){
        uni.getUserProfile({
          desc:"登入商城",
          success:(res) => {
            this.updateUserInformation(res)
            //傳進函數獲得token
            this.getToken(res)},
          fail:(res) => {if(res.errMsg === 'getUserProfile:fail auth deny') return uni.$showMessage('不给权限怎么登陸啊!')}
        })
      },
      async getToken(userData){
        //獲取code值
        const [err, res] = await uni.login().catch(err => err)
        if(err || res.errMsg !== 'login:ok') return uni.$showMessage('登入失败')
        
        //參數
        const userInfoList = {
          code : res.code,//用戶登陸凭證
          encryptedData: userData.encryptedData,//用戶信息密文
          iv: userData.iv,//加密算法初始向量
          rawData: userData.rawData,//用戶信息數據字符串
          signature:userData.signature//用sha1得到字符串，signature = sha1( rawData + session_key )
        }
        const {data : loginResult} = await uni.$http.post('user/login',userInfoList)
        if(loginResult.meta.status !== 200) return uni.$showMessage('登入失败!')
        //保存token到vuex
        this.updateToken(loginResult.message.token)
        this.navigateBack()
      },
      navigateBack(){
        if(this.redirectInfo && this.redirectInfo.openType === 'switchTab'){
          uni.switchTab({
            url:this.redirectInfo.from,
            complete:() => {
              this.updateRedirectInfo(null)
            }
          })
        }
      }
    },
    computed:{
      ...mapState('user',['redirectInfo'])
    }
  }
</script>

<style lang="scss">
  .login-page{
    height: 750rpx;
    background-color: #F8F8F8;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .login-button{
      width: 60%;
      border-radius:20px;
      margin: 15px 0;
    }
    .login-text{
      font-size: 12px;
      color:gray;
    }
    
  }

</style>
